import React, { useState, useEffect } from 'react';
import { Container, Form, Button, Alert } from 'react-bootstrap';

const publishUrl = process.env.REACT_APP_PUBLISH_URL;

const Publish = () => {
  const [imagePath, setImagePath] = useState('');
  const [title, setTitle] = useState('');
  const [summary, setSummary] = useState('');
  const [publishDate, setPublishDate] = useState('');
  const [source, setSource] = useState('');
  const [body, setBody] = useState('');
  const [success, setSuccess] = useState(false);
  const [errors, setErrors] = useState({});

  const validateForm = () => {
    const newErrors = {};
    if (!imagePath) newErrors.imagePath = '图片路径是必填项';
    if (!title) newErrors.title = '标题是必填项';
    if (!summary) newErrors.summary = '概述是必填项';
    if (!publishDate) newErrors.publishDate = '发布时间是必填项';
    if (!source) newErrors.source = '来源是必填项';
    if (!body) newErrors.body = '正文是必填项';
    return newErrors;
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    const errors = validateForm();
    setErrors(errors); // 更新错误信息
    if (Object.keys(errors).length > 0) {
      return; // 如果有错误，则不提交表单
    }

    const token = localStorage.getItem('token');
    if (!token) {
      alert('未登录或登录已过期');
      return;
    }

    const formattedDate = formatDateTime(publishDate);
    const response = await fetch(publishUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify({
        image_path: imagePath,
        title: title,
        summary: summary,
        publish_date: formattedDate,
        source: source,
        body: body,
      }),
    });
    const data = await response.json();
    if (response.ok) {
      setSuccess(true); // 显示成功提示
      setImagePath(''); // 清空图片路径
      setTitle(''); // 清空标题
      setSummary(''); // 清空概述
      setPublishDate(''); // 清空发布时间
      setSource(''); // 清空来源
      setBody(''); // 清空正文
    } else {
      alert('发布失败: ' + data.error); // 显示错误信息
    }
  };

  useEffect(() => {
    if (success) {
      // 显示成功提示
      setTimeout(() => {
        setSuccess(false); // 隐藏成功提示
      }, 3000);
    }
  }, [success]);

  const formatDateTime = (dateTime) => {
    const date = new Date(dateTime);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  };

  return (
    <Container className="mt-5">
      <h1>发布新闻</h1>
      <Form onSubmit={handleSubmit}>
        <Form.Group controlId="publishImage">
          <Form.Label>新闻图片路径：</Form.Label>
          <Form.Control
            type="text"
            placeholder="请输入新闻图片路径"
            value={imagePath}
            onChange={(e) => {
              setImagePath(e.target.value);
              setErrors((prevErrors) => ({ ...prevErrors, imagePath: '' }));
            }}
            isValid={!errors.imagePath}
            isInvalid={!!errors.imagePath}
          />
          <Form.Control.Feedback type="invalid">
            {errors.imagePath}
          </Form.Control.Feedback>
        </Form.Group>
        <Form.Group controlId="publishTitle">
          <Form.Label>新闻标题：</Form.Label>
          <Form.Control
            type="text"
            placeholder="请输入新闻标题"
            value={title}
            onChange={(e) => {
              setTitle(e.target.value);
              setErrors((prevErrors) => ({ ...prevErrors, title: '' }));
            }}
            isValid={!errors.title}
            isInvalid={!!errors.title}
          />
          <Form.Control.Feedback type="invalid">
            {errors.title}
          </Form.Control.Feedback>
        </Form.Group>
        <Form.Group controlId="publishSummary">
          <Form.Label>新闻概述：</Form.Label>
          <Form.Control
            type="text"
            placeholder="请输入新闻概述"
            value={summary}
            onChange={(e) => {
              setSummary(e.target.value);
              setErrors((prevErrors) => ({ ...prevErrors, summary: '' }));
            }}
            isValid={!errors.summary}
            isInvalid={!!errors.summary}
          />
          <Form.Control.Feedback type="invalid">
            {errors.summary}
          </Form.Control.Feedback>
        </Form.Group>
        <Form.Group controlId="publishDate">
          <Form.Label>发布时间：</Form.Label>
          <Form.Control
            type="datetime-local"
            placeholder="请选择发布时间"
            value={publishDate}
            onChange={(e) => {
              setPublishDate(e.target.value);
              setErrors((prevErrors) => ({ ...prevErrors, publishDate: '' }));
            }}
            isValid={!errors.publishDate}
            isInvalid={!!errors.publishDate}
          />
          <Form.Control.Feedback type="invalid">
            {errors.publishDate}
          </Form.Control.Feedback>
        </Form.Group>
        <Form.Group controlId="publishSource">
          <Form.Label>新闻来源：</Form.Label>
          <Form.Control
            type="text"
            placeholder="请输入新闻来源"
            value={source}
            onChange={(e) => {
              setSource(e.target.value);
              setErrors((prevErrors) => ({ ...prevErrors, source: '' }));
            }}
            isValid={!errors.source}
            isInvalid={!!errors.source}
          />
          <Form.Control.Feedback type="invalid">
            {errors.source}
          </Form.Control.Feedback>
        </Form.Group>
        <Form.Group controlId="publishBody">
          <Form.Label>新闻正文：</Form.Label>
          <Form.Control
            as="textarea"
            rows={3}
            placeholder="请输入新闻正文"
            value={body}
            onChange={(e) => {
              setBody(e.target.value);
              setErrors((prevErrors) => ({ ...prevErrors, body: '' }));
            }}
            isValid={!errors.body}
            isInvalid={!!errors.body}
          />
          <Form.Control.Feedback type="invalid">
            {errors.body}
          </Form.Control.Feedback>
        </Form.Group>
        <Button variant="primary" type="submit">
          发布
        </Button>
      </Form>
      {success && (
        <Alert variant="success" onClose={() => setSuccess(false)} dismissible>
          新闻发布成功！
        </Alert>
      )}
    </Container>
  );
};

export default Publish;